package com.zmm.util.auth.model;

import com.zmm.common.exception.handle.CustomRunTimeException;
import org.springframework.stereotype.Component;

/**
 * @author 900045
 * @description:
 * @name Operator
 * @date By 2021-07-06 09:30:55
 */
@Component
public class Operator {

	/**
	 * 存储单次请求里的会员信息
	 */
	private ThreadLocal<UserForAuth> threadLocal   = new ThreadLocal<>();

	public Operator() {}

	/**
	 * 获取当前用户信息  登陆成功时保存
	 * @author: 900045
	 * @date: 2021-06-04 16:22:45
	 * @throws
	 * @return: com.zmm.util.auth.model.UserForAuth
	 **/
	public UserForAuth fetchUser() {
		UserForAuth user = userOrNull();
		if (user == null) {
			throw new CustomRunTimeException("未登录,请登录后操作");
		}
		return user;
	}

	/**
	 * 从线程池中获取
	 * @author: 900045
	 * @date: 2021-06-04 16:23:08
	 * @throws

	 * @return: com.zmm.util.auth.model.UserForAuth
	 **/
	public UserForAuth userOrNull() {
		return threadLocal.get();
	}

	/**
	 * 获取用户的ID
	 * @author: 900045
	 * @date: 2021-06-04 16:23:58
	 * @throws

	 * @return: java.lang.Integer
	 **/
	public Integer fetchUserId() {
		return fetchUser().getUserId();
	}

	/**
	 * 获取用户 名称
	 * @return
	 */
	public String fetchUserName(){
		return fetchUser().getUserName();
	}

	/**
	 * 获取 用户的角色
	 * @author: 900045
	 * @date: 2021-06-04 16:23:41
	 * @throws

	 * @return: java.lang.Integer
	 **/
	public Integer fetchRoleId() {
		return fetchUser().getRoleId();
	}

	/**
	 * 获取用户角色名称
	 * @author: 900045
	 * @date: 2021-06-07 16:16:03
	 * @throws

	 * @return: java.lang.String
	 **/
	public String fetchRoleName(){
		return fetchUser().getRoleName();
	}

	/**
	 * 在当前线程添加 用户id 仅允许在认证中（AbstractAuthInterceptor）使， 其他不能使用
	 * @author: 900045
	 * @date: 2021-06-04 16:24:33
	 * @throws
	 * @param user: 
	 * @return: void
	 **/
	public void addThread(UserForAuth user) {
		if (user == null || user.getUserId() <= 0) {
			return;
		}
		threadLocal.set(user);
	}

	public void clean() {
		threadLocal.remove();
		//TODO 临时解决
	}
}
